package com.az.emailcommon.util;

import jakarta.mail.internet.MimeMessage;
import lombok.Data;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.nio.file.Files;
import java.nio.file.Paths;


@Data
public class EmailSender {

    private EmailSender(){}
    private static EmailSender instance;
    public static synchronized EmailSender getInstance()
    {
        if(instance == null)
        {
            instance = new EmailSender();
        }
        return instance;
    }


    private JavaMailSender javaMailSender;


    private String emailFrom;


    public void sendSimpleEmail(String to, String subject, String msg) {
        SimpleMailMessage simpleMessage = new SimpleMailMessage();
        simpleMessage.setFrom(emailFrom);
        simpleMessage.setSubject(subject);
        simpleMessage.setText(msg);
        simpleMessage.setTo(to);
        javaMailSender.send(simpleMessage);
    }

    //带附件的邮件

    public void sendEmailWithAttachment(
            String emailTo, String subject, String text, String fileName, String filePath)

            throws org.springframework.mail.MailSendException, jakarta.mail.MessagingException {


        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,
                true);

        //编辑邮件信息
        mimeMessageHelper.setTo(emailTo);
        mimeMessageHelper.setFrom(emailFrom);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(text);
        mimeMessageHelper.addAttachment(fileName, () -> Files.newInputStream(Paths.get(filePath)),
                "application/octet-stream");

        javaMailSender.send(mimeMessage);


    }

    //html邮件

    public void sendHTMLEmail(String emailTo, String subject, String msg)
            throws org.springframework.mail.MailSendException, jakarta.mail.MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,
                true);

        //编辑邮件信息
        mimeMessageHelper.setTo(emailTo);
        mimeMessageHelper.setFrom(emailFrom);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(msg, true);
        javaMailSender.send(mimeMessage);
    }
}
